<template>
  <view
    class="hoverBallBox"
    :style="{
      width: `${diameter}px`,
      height: `${diameter}px`,
      top: `${top}px`,
      left: `${left}px`
    }"
    @touchmove="touchmove"
    @touchend="touchend"
    @touchcancel="touchcancel"
    @click.stop="scanCode"
    :animation="ballAnimation">
      <image
      src="@/static/image/icon/addHospital.png"
      mode="widthFix"
      class="h-auto"
      :style="`width: ${diameter}px;`" />
  </view>
</template>

<script setup lang="ts">
const diameter = ref(60) // 图标大小
const top = ref(0)
const left = ref(0)
const paddingX = ref(20) // 左右边距
const paddingY = ref(10) // 上下边距
const isMove = ref(false)
const timeout = ref<any>()

const ballAnimation = ref<any>({})
const modile = uni.$u.sys() as any
const init = async () => {
  await nextTick()
  top.value = modile.safeArea.height - unref(diameter) * 2 // 初始位置
  left.value = modile.safeArea.width - unref(diameter) - 20 // 初始位置
}

init()

const scanCode = () => {
  uni.$u.route({
    type: 'navigateTo',
    url: '/pages/organization/editOrganization'
  })
};

const touchmove = (e: any) => {
  isMove.value = true
  if (unref(timeout) != null) {
    clearTimeout(unref(timeout))
    timeout.value = null
  }
  let touch = e.touches[0] || e.changedTouches[0]
  left.value = touch.clientX
  top.value = touch.clientY
  console.log(1)
}

const touchend = (e: any) => {
  if (!unref(isMove)) {
    return
  }
  finish(e)
}

const touchcancel = (e: any) => {
  if (!unref(isMove)) {
    return
  }
  finish(e)
}

const finish = (e: any) => {
  isMove.value = false
  let touch = e.touches[0] || e.changedTouches[0]
  left.value = touch.clientX
  top.value = touch.clientY
  let x = '0'

  if (2 * unref(left) + unref(diameter) >= modile.safeArea.width) {
    // 右侧滑动出屏幕外,归位
    left.value = modile.safeArea.width - unref(diameter) - unref(paddingX)
  } else {
    // 左侧滑动出屏幕外,归位
    left.value = unref(paddingX)
  }
  if (unref(top) > modile.safeArea.height - unref(diameter) - unref(paddingY)) {
    // 底部划出最大高度,归位
    top.value = modile.safeArea.height - unref(diameter) - unref(paddingY)
  } else if (unref(top) < modile.navbarHeight + unref(paddingY)) {
    // 顶部划出最小高度,归位
    top.value = modile.navbarHeight + unref(paddingY)
  }
  let create = uni.createAnimation({
    duration: 0
  })
  create.translate(x).step()
  ballAnimation.value = create.export()
}
</script>

<style lang="scss" scoped>
.hoverBallBox {
  position: fixed;
  z-index: 20;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
</style>
